<?php

//接口

//注册动作
// 添加Ajax请求处理函数 - 保存选项
add_action('wp_ajax_save_api_dev_demo_option_callback', 'save_api_dev_demo_option_callback');

function save_api_dev_demo_option_callback()
{
    // 获取通过 Ajax POST 请求传递的对象数据
    $object_data = $_POST['object_data'];

    //将 JSON 字符串解析为数组，方便后续传给JS
    $array = json_decode(stripslashes($object_data), true);

    // 保存设置选项
    update_option('API_DEV_OPTION', $array);

    // 发送成功响应
    $response = array(
        'message' => '设置选项已保存！',
        'object' => $array,
    );
    wp_send_json_success($response);
}

//接口查询值
add_action('wp_ajax_nopriv_get_xh_callback', 'get_xh_callback');
add_action('wp_ajax_get_xh_callback', 'get_xh_callback');

function get_xh_callback()
{
    $config = get_option('API_DEV_OPTION');
    $key = $config['key'];
    $url = 'https://api.topthink.com/xinhua/query';
    $data = [
        'word' => $_POST['word']
    ];
    $data = wp_json_encode($data);

    $options = [
        'body' => $data,
        'headers' => [
            'Content-Type' => 'application/json',
            'Authorization' => 'AppCode ' . $key
        ]
    ];
    // 发起请求
    $response = wp_remote_post($url, $options);

    if (!is_wp_error($response) && $response['response']['code'] === 200) {
        $content = json_decode($response['body'], true);
        wp_send_json_success($content);
    } else {
        wp_send_json_error('请求出错');
        error_log('请求出错');
    }
}


